(async function() {
	//命令行解析
	const {
		ParamFormat
	} = require("./ParamFormat.js"),
		//命令行参数
		paramFormat = new ParamFormat(),
		//文件系统
		fs = require('fs'),
		//网络
		net = require('net');
	/**
	 * 文本读取
	 * @param {string} path
	 */
	function readText(path) {
		return new Promise((call) => {
			fs.readFile(path, 'utf8', function(err, data) {
				call(err == null ? data : null);
			});
		});
	}

	function isCloseSocket(socket) {
		return socket["_writableState"].closed;
	}

	function createClient(host, port) {
		const tcpClient = net.Socket();
		return new Promise((call) => {
			let isCall = true;
			tcpClient.on('error', (e) => {
				if (isCall) {
					console.log(`tcpClient open fail--${host}:${port}`);
					isCall = false;
					call(tcpClient);
				}
			});
			tcpClient.connect(port, host, function() {
				if (isCall) {
					console.log(`tcpClient open success--${host}:${port}`);
					isCall = false;
					call(tcpClient);
				}
			});
		});
	}

	async function parseAgentConfig() {
		let str = await readText('./app.cfg', 'utf8');
		let input = paramFormat.getValue("-s", str == null ? null : "");
		str = `${str}
				${input}
				`;
		let res = [];
		str.split(/[\r\n]/).forEach((a) => {
			a.trim().split(",").forEach((b) => {
				if (/(.+):(\d+?)\-(\d+)/.exec(b)) {
					let host = RegExp.$1;
					let targetPort = parseInt(RegExp.$2);
					if (targetPort < 1) {
						throw `你是傻逼吗?端口${targetPort}不可用`;
					}
					let proxytPort = parseInt(RegExp.$3);
					res.forEach((c) => {
						if (proxytPort == c.proxytPort) {
							throw `${b}中代理端口${proxytPort}已存在`;
						}
					});
					if (proxytPort < 1) {
						throw `你是傻逼吗?端口${proxytPort}不可用`;
					}
					res.push({
						host,
						targetPort,
						proxytPort
					});
				}
			});
		});
		return res;
	}

	//获得配置
	(await parseAgentConfig()).forEach((config) => {
		net.createServer(async function(socket) {
			const tcpClient = await createClient(config.host, config.targetPort);
			//客户端事件
			if (isCloseSocket(tcpClient)) {
				socket.destroy();
				console.log(`target ${config.host}:${config.targetPort},open fail`);
				return;
			}
			tcpClient.on('data', function(data) {
				if (isCloseSocket(socket)) {
					socket.destroy();
					console.log(`user Active disconnect`);
					return;
				}
				socket.write(data);
			});

			function onClientOffLine() {
				console.log(`target offLine----`);
				socket.destroy();
			}
			tcpClient.on('error', onClientOffLine);
			tcpClient.on('close', onClientOffLine);
			//服务端口事件
			socket.on('data', function dataHandler(data) { //data是客户端发送给服务器的数据
				let close = tcpClient["_writableState"].closed;
				if (close) {
					console.log(`target close:${close}`);
					tcpClient.destroy();
				} else {
					tcpClient.write(data);
				}
			});
			socket.on('error', function(e) {
				console.log(`socket error:${e}`);
				tcpClient.destroy();
				socket.destroy();
			});
			socket.on('close', function() {
				tcpClient.destroy();
				console.log('user clise');
			});
		}).listen(config.proxytPort);
		console.log(`port ${config.proxytPort}listen success-------`);
	});
})();
